#include "logger.h"
#define N 10

int qid, vers = 0, count = 0;
struct message {
	long mtype;
	char text[100];
} msg;





void log_init (char* version) // version - DEBUG or RELEASE
{ 
	freopen ("log.txt","w",stdout);
	if (strcmp (version, "RELEASE") == 0) vers = 1;
	if ((qid = msgget(IPC_PRIVATE, IPC_CREAT | 0666)) < 0)
	{
		printf ("Error: creating a queue");
		exit (-1);
	}
}
void msg_print ()
{

	long msgtyp = 1;
	if (msgrcv (qid, (void *) &msg, sizeof(msg.text), msgtyp, MSG_NOERROR | IPC_NOWAIT) < 0)
	{
		printf ("Error: recieving a message");
		exit (-1);
	}
	printf ("%s\n", msg.text);
	count--;
}	

void log_print (char* path, int line, char* er_type, char* mtext)
{
	if ((vers == 0) || (strcmp (er_type, "ERROR") == 0))
	{
		msg.mtype = 1;
		sprintf (msg.text, "%s:%d: %s: %s", path, line, er_type, mtext);
		if (msgsnd (qid, &msg, sizeof(msg.text), 0) != 0)
		{
		    printf ("Error: sending a message");
		    exit (-1);
		}
		count++;
		if (count > N) 
			while (count > 0)
				msg_print();
	}
}

	
void log_end()
{
	if (count > 0)
		while (count > 0)
				msg_print();
	if ((msgctl( qid, IPC_RMID, NULL)) != 0)
	{
		printf ("Error: closing the queue");
		exit (-1);
	}
}
